<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Menashop
 * @package    Menashop_XML_Parser
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * The parser for XML
 * 
 * @category   Menashop
 * @package    Menashop_XML_Parser
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Menashop_XML_Parser
{

    /**
     * The SAX object
     * @var object
     */
    private $_object;

    /**
     * The file path
     * @var string 
     */
    private $_filePath;

    /**
     * The logger
     * @var object 
     */
    private $_logger;

    /**
     * Initialize the SAX parser for XML
     * @param type $object
     * @param type $filePath 
     */
    public function __construct($object, $filePath)
    {
        $this->_object = $object;
        $this->_filePath = $filePath;
        $this->_logger = Zend_Registry::get('log');
    }

    /**
     * Parse a XML file
     */
    public function parseXML()
    {
        $xml = xml_parser_create();
        xml_set_object($xml, $this->_object);
        xml_set_element_handler($xml, 'startElement', 'endElement');
        xml_set_character_data_handler($xml, 'characterData');
        xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, false);
        $fp = fopen($this->_filePath, 'r');
        // check file
        if (!$fp) {
            $this->_logger->crit(__METHOD__ . " can't read XML data");
            return false;
        }
        // read blocks from file 
        while ($data = fread($fp, 4096)) {
            // try to parse
            if (!xml_parse($xml, $data, feof($fp))) {
                $this->_logger->crit(__METHOD__ . " can't parse XML data: " . xml_error_string(xml_get_error_code($xml)) . " at line " . xml_get_current_line_number($xml));
                return false;
            }
        }
        fclose($fp);
        xml_parser_free($xml);
        return true;
    }

}

